<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view>
		<cu-custom :bgColor="'bg-'+theme.backgroundColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">砍价确认订单</block>
		</cu-custom>
		<view class="margin-bottom-bar">
			<view class="cu-list cu-card menu-avatar">
				<view class="cu-item padding-left delivery-way">
					<radio-group @change="deliveryWayChange">
						<radio class="red margin-right-xs" checked value="1"></radio>普通快递<radio class="red margin-left-sm margin-right-xs"
						 value="2"></radio>上门自提
					</radio-group>
				</view>
				<navigator class="cu-item" url="/pages/user/user-address/list/index?select=true" v-if="orderSubParm.deliveryWay == '1'">
					<view class="cu-avatar round cuIcon-location bg-orange"></view>
					<view class="content loc-content" v-if="userAddress">
						<view class="flex">
							<view class="text-black">{{userAddress.userName}}</view>
							<view class="text-gray text-sm margin-left-sm">{{userAddress.telNum}}</view>
						</view>
						<view class="text-black text-sm overflow-2 loc-info">
							<view class="cu-tag bg-red radius text-xs margin-right-xs" v-if="userAddress.isDefault == '1'">默认</view>
							<text class="text-gray">{{userAddress.provinceName}}{{userAddress.cityName}}{{userAddress.countyName}}{{userAddress.detailInfo}}</text>
						</view>
					</view>
					<view class="content loc-content" v-if="!userAddress">请选择收货地址</view>
					<view class="action">
						<text class="cuIcon-right"></text>
					</view>
				</navigator>
			</view>
			<view class="cu-card article mar-top-30">
				<view class="cu-item">
					<view class="cu-list menu">
						<view class="cu-item list-item" v-for="(item, index) in orderConfirmData" :key="index">
							<view class="flex align-center">
								<view class="content response align-center">
									<image :src="item.picUrl ? item.picUrl : '/static/public/img/no_pic.png'" mode="aspectFill"
									 class="row-img margin-top-xs basis-3"></image>
									<view class="desc row-info basis-7 padding-left-xs overflow-2">
										<view class="text-black text-df margin-top-sm">{{item.spuName}}</view>
										<view class="text-gray text-sm margin-top-xs cu-tag round" style="white-space: normal;height: auto;" v-if="item.specInfo">{{item.specInfo}}</view>
										<view class="flex margin-top-xs align-center">
											<view class="flex-sub">
												<text class="text-price text-xl text-bold text-red margin-top-sm">{{item.salesPrice}}</text>
											</view>
											<view class="flex-twice text-right">x{{item.quantity}}</view>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view class="cu-item margin-top-sm">
							<view class="">
								<text class="text-gray text-sm">订单金额</text>
							</view>
							<view class="action">
								<view class="text-price">{{salesPrice}}</view>
							</view>
						</view>
						<view class="cu-item margin-top-sm">
							<view class="">
								<text class="text-gray text-sm">运费金额</text>
							</view>
							<view class="action">
								<view class="text-price">{{freightPrice}}</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="cu-card mar-top-30">
				<view class="cu-item cu-form-group align-start">
					<input @input="userMessageInput" placeholder="给卖家留言"></input>
				</view>
			</view>
		</view>
		<view class="cu-bar bg-white border foot">
			<view class="flex response">
				<view class="flex-sub"></view>
				<view class="flex-treble bar-rt">
					<text class="text-sm text-gray">共{{ orderConfirmData.length }}件，</text>
					<text class="text-sm text-gray">合计：</text>
					<text class="text-xl text-bold text-price text-red">{{numberUtil.numberAddition(paymentPrice,freightPrice)}}</text>
					<button class="cu-btn round lg margin-left-sm shadow-blur" :class="'bg-'+theme.themeColor" @tap="orderSub" :loading="loading" :disabled="loading" type>提交订单</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	const app = getApp();
	import api from 'utils/api'
	import numberUtil from 'utils/numberUtil.js'

	export default {
		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				numberUtil: numberUtil,
				orderConfirmData: [],
				salesPrice: 0,
				paymentPrice: 0,
				freightPrice: 0,
				userAddress: null,
				orderSubParm: {
					paymentType: '1',
					deliveryWay: '1'
				},
				loading: false,
				freightMap: new Map() //各运费模块计数
			};
		},

		components: {},
		props: {},

		onShow() {},

		onLoad: function() {
			this.numberUtil = numberUtil;
			this.userAddressPage();
			this.orderConfirmDo();
		},
		methods: {
			//订单提交成功后处理
			orderSubAfter(data) {
				let that = this
				// #ifdef MP-WEIXIN
				//微信小程序订阅消息
				api.wxTemplateMsgList({
					enable: '1',
					useTypeList: ['2', '3']
				}).then(res => {
					let tmplIds = [];
					res.data.forEach(item => {
						tmplIds.push(item.priTmplId);
					});
					uni.requestSubscribeMessage({
						tmplIds: tmplIds,
						success(res) {
							console.log(res);
						},
						complete() {
							that.toOrderPage(data)
						}

					});
				});
				// #endif
				// #ifndef MP-WEIXIN
				//非微信小程序
				that.toOrderPage(data)
				// #endif
			},
			toOrderPage(data){
				if(data.length > 1){//订单被拆分，跳订单列表页
					uni.redirectTo({
						url: '/pages/order/order-list/index?status=0'
					});
				}
				if(data.length == 1){//跳订单详情页
					uni.redirectTo({
						url: '/pages/order/order-detail/index?callPay=true&id=' + data[0].id
					});
				}
			},

			deliveryWayChange(e) {
				this.orderSubParm.deliveryWay = e.detail.value;
				this.freightMap = new Map();
				this.orderConfirmDo();
			},

			orderConfirmDo() {
				// 本地获取参数信息
				let that = this;
				uni.getStorage({
					key: 'param-orderConfirm',
					success: function(res) {
						let orderConfirmData = res.data;
						let salesPrice = 0; //订单金额

						let freightPrice = 0; //运费

						orderConfirmData.forEach((orderConfirm, index) => {
							salesPrice = (Number(salesPrice) + orderConfirm.salesPrice * orderConfirm.quantity).toFixed(2);
							orderConfirm.paymentPrice = (orderConfirm.salesPrice * orderConfirm.quantity).toFixed(2); //计算运费

							let freightTemplat = orderConfirm.freightTemplat;

							if (freightTemplat) {
								if (freightTemplat.type == '1') {
									//模板类型1、买家承担运费
									let quantity = orderConfirm.quantity;

									if (freightTemplat.chargeType == '1') {
										//1、按件数；
										that.countFreight(orderConfirm, freightTemplat, quantity);
									} else if (freightTemplat.chargeType == '2') {
										//2、按重量
										let weight = orderConfirm.weight;
										that.countFreight(orderConfirm, freightTemplat, (weight * quantity));
									} else if (freightTemplat.chargeType == '3') {
										//3、按体积
										let volume = orderConfirm.volume;
										that.countFreight(orderConfirm, freightTemplat, (volume * quantity));
									}
								} else {
									orderConfirm.freightPrice = 0;
								}
							} else {
								orderConfirm.freightPrice = 0;
							}

							freightPrice = (Number(freightPrice) + Number(orderConfirm.freightPrice)).toFixed(2);
						});

						if (that.orderSubParm.deliveryWay == '2') {
							//自提不算运费
							freightPrice = 0;
						}
						that.orderConfirmData = orderConfirmData;
						that.salesPrice = salesPrice;
						that.freightPrice = freightPrice;
						that.paymentPrice = salesPrice;
					}
				});
			},

			//计算运费
			countFreight(orderConfirm, freightTemplat, quantity) {
				let freightMap = this.freightMap
				let freightMapValue = 0
				if (freightMap.has(freightTemplat.id)) {
					freightMapValue = freightMap.get(freightTemplat.id)
				}
				quantity = quantity + freightMapValue
				freightMap.set(freightTemplat.id, quantity)
				this.freightMap = freightMap
				let firstNum = freightTemplat.firstNum;
				let firstFreight = freightTemplat.firstFreight;
				let continueNum = freightTemplat.continueNum;
				let continueFreight = freightTemplat.continueFreight;

				if (quantity <= firstNum) {
					//首件之内数量
					orderConfirm.freightPrice = firstFreight;
					if (freightMapValue > 0) { //同一运费模板已有商品算了运算，并在首件之内，当前商品不算运费
						orderConfirm.freightPrice = 0
					}
				} else {
					//首件之外数量
					let num = quantity - firstNum;
          let val1 = continueNum > 0 ? num / continueNum : 0//不能为0
					orderConfirm.freightPrice = (Number(firstFreight) + Math.ceil(val1) * continueFreight).toFixed(2);
					if (freightMapValue > 0) { //同一运费模板已有商品算了运算，并超过了首件数量，当前商品只算超出运费
						if (freightMapValue >= firstNum) {
							num = quantity - freightMapValue - (freightMapValue - firstNum) % continueNum
						} else {
							num = quantity - freightMapValue - (firstNum - freightMapValue)
						}
            let val2 = continueNum > 0 ? num / continueNum : 0//不能为0
						orderConfirm.freightPrice = (Math.ceil(val2) * continueFreight).toFixed(2)
					}
				}
			},

			setUserAddress(obj) {
				this.userAddress = obj;
			},
			//获取默认收货地址
			userAddressPage() {
				api.userAddressPage({
					searchCount: false,
					current: 1,
					size: 1,
					isDefault: '1'
				}).then(res => {
					let records = res.data.records;

					if (records && records.length > 0) {
						this.userAddress = records[0];
					}
				});
			},

			userMessageInput(e) {
				this.orderSubParm.userMessage = e.detail.value;
			},

			//提交订单
			orderSub() {
				let that = this;
				let userAddress = that.userAddress;

				if (that.orderSubParm.deliveryWay == '1' && userAddress == null) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				that.loading = true;
				let orderSubParm = that.orderSubParm;
				let orderConfirmData = that.orderConfirmData;
				orderSubParm.skus = orderConfirmData;
				orderSubParm.orderType = orderConfirmData[0].orderType;
				orderSubParm.marketId = orderConfirmData[0].marketId;
				orderSubParm.relationId = orderConfirmData[0].relationId;
				api.orderSub(Object.assign({}, {
					userAddressId: that.orderSubParm.deliveryWay == '1' ? userAddress.id : null
				}, orderSubParm)).then(res => {
					that.orderSubAfter(res.data);
				}).catch(() => {
					that.loading = false;
				});
			}

		}
	};
</script>
<style>
	.bar-rt {
		text-align: right !important;
		margin-right: 10rpx !important
	}

	.row-img {
		width: 200rpx !important;
		height: 200rpx !important;
		border-radius: 10rpx
	}

	.row-info {
		display: block !important;
	}

	.loc-content {
		width: calc(100% - 96rpx - 60rpx - 80rpx) !important;
		left: 126rpx !important
	}

	.loc-info {
		line-height: 1.4em
	}

	.list-item {
		display: block !important;
		padding: 6rpx !important;
	}

	.cu-list.menu>.cu-item:after {
		border-bottom: unset !important
	}

	.cu-list.menu>.cu-item {
		min-height: unset !important
	}

	.delivery-way {
		justify-content: unset !important
	}
</style>
